<template>
  <!-- 选择元素 -->
  <el-dialog v-el-drag-dialog :title="listForm.title" :close-on-click-modal="false" v-model="listForm.open"
             width="1300px" append-to-body>
    <el-container>
      <el-main>
        <el-form v-if="listForm.searchColumn &&listForm.searchColumn.length>0" ref="queryForm" :inline="true"
                 label-width="120px" label-position="right" label-suffix=":">
          <el-row>
            <el-col :span="9" v-for="item in listForm.searchColumn">
              <el-form-item :label="item['label']" :prop="item['prop']">
                <el-input v-model="queryParams[item['prop']]" placeholder="请输入元素名称" clearable size="small"
                          @keyup.enter.native="handleQuery"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <search-button @click="handleQuery"/>
                <reset-button @click="resetQuery"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table v-loading="loading" :data="dataList" highlight-current-row @current-change="handleCurrentChange"
                  @row-click="clickRow" @selection-change="handleSelectionChange" ref="multipleTable">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="序号" type="index" align="center">
            <template slot-scope="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column v-for="(column, index) in columns" :key="index" :prop="column.prop" show-overflow-tooltip
                           min-width="120"
                           :label="column.label"></el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>
      </el-main>
      <el-aside width="120px" style="background: #fff;display: flex;align-items: center;border-left:  1px solid #eee">
        <el-button-group style="margin-left:15%">
          <el-button size="small" @click="moveUp">上移</el-button>
          <el-button size="small" @click="moveDown" style="margin-top: 5px">下移</el-button>
          <el-button size="small" @click="selectEvent" style="margin-top: 5px">选择</el-button>
          <el-button size="small" @click="removeEvent" style="margin-top: 5px">删除</el-button>
          <el-button size="small" @click="emptyEvent" style="margin-top: 5px">清空</el-button>
        </el-button-group>
      </el-aside>
      <el-aside class="el-aside select-aside" width="200px" style="background: #fff;border-left: 1px solid #eee">
        <el-header class="select-header" height="40px">
          <span style="font-size: 14px">已选择</span>
        </el-header>
        <div>
          <el-tree ref="tree" :data="selectData" show-checkbox :props="defaultProps" check-on-click-node></el-tree>
        </div>
      </el-aside>

    </el-container>
    <dialog-footer slot="footer" @ok="submitForm" @cancel="cancel"/>
  </el-dialog>
</template>

<script>
import {debounceWrapper} from "@/utils/zmids";
import {deepClone} from "@/utils";

export default {
  name: "listDialog",
  props: ['listForm', 'item'],
  data() {
    return {
      dictOptions: [],
      selectData: [],
      defaultProps: {
        children: 'children',
        label: ''
      },
      multipleSelection: [],
      currentRow: {},//选中数据
      loading: false,
      // 总条数
      total: 0,
      dataList: [],
      columns: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
    }
  },
  methods: {
    clickRow(row) {
      // 多选选中行
      // 根据id判断当前点击的是否被选中
      const selected = this.multipleSelection.some(item => item[this.listForm.valueField] === row[this.listForm.valueField] || item[this.listForm.showField] === row[this.listForm.showField])
      if (!selected) {
        // 选择
        this.multipleSelection.push(row)
        this.$refs.multipleTable.toggleRowSelection(row, true);
      } else {
        // 取消
        var finalArr = this.multipleSelection.filter((item) => {
          return item[this.listForm.valueField] !== row[this.listForm.valueField] || item[this.listForm.showField] !== row[this.listForm.showField]
        })
        // 取消后剩余选中的
        this.multipleSelection = finalArr
        this.$refs.multipleTable.toggleRowSelection(row, false);
      }
    },
    moveHandler(key) {
      const checkData = this.$refs.tree.getCheckedNodes();
      if (checkData.length > 0) {
        let index = 0
        if (this.listForm.valueField) {
          index = this.selectData.findIndex(i => i[this.listForm.valueField] === checkData[0][this.listForm.valueField]);
        } else {
          index = this.selectData.findIndex(i => i[this.listForm.showField] === checkData[0][this.listForm.showField]);
        }
        let removedItems = this.selectData.splice(index, checkData.length);
        this.selectData = this.selectData.slice(0, key === 'up' ? index - 1 : index + 1).concat(removedItems, this.selectData.slice(key === 'up' ? index - 1 : index + 1));
      }
    },
    moveUp() {
      this.moveHandler('up');
    },
    moveDown() {
      this.moveHandler('down');
    },
    selectEvent() {
      const is_in_array = (array, obj) => {
        for (let item of array) {
          if (item[this.listForm.valueField] === obj[this.listForm.valueField] || item[this.listForm.showField] === obj[this.listForm.showField]) {
            return true;
          }
        }
        return false;
      };
      // 在数组中添加对象
      const concat = (array, obj) => {
        if (!is_in_array(array, obj)) {
          array.push(obj);
        }
      };

      // let data = deepClone(this.listForm.multiple ? this.multipleSelection : [this.currentRow]);
      let data = deepClone(this.multipleSelection);
      data.map((e) => {
        concat(this.selectData, e);
      })
    },
    removeEvent() {
      const checkData = this.$refs.tree.getCheckedNodes();
      if (checkData.length == 0) return this.$message.error("请勾选需要删除的数据！");
      this.selectData = this.selectData.filter((e) => {
        return !checkData.includes(e)
      })
    },
    emptyEvent() {
      this.selectData = [];
    },
    snakeToCamel(str) {
      return str.replace(/_\w/g, function (match) {
        return match[1].toUpperCase();
      });
    },
    setQueryParams() {
      let searchData = deepClone(this.queryParams)
      this.listForm.searchColumn.map((e) => {
        const searchType = this.listForm.searchType;
        if (!searchType) {
          if (searchData[e.prop]) {
            searchData[this.snakeToCamel(e.prop)] = searchData[e.prop];
            searchData[`${this.snakeToCamel(e.prop)}Like`] = searchData[e.prop];
          }
        } else {
          let typeList = searchType.split(',');
          typeList.map((item) => {
            if (item == 'like') {
              searchData[`${this.snakeToCamel(e.prop)}Like`] = searchData[e.prop];
            } else if (item == 'upper') {
              searchData[this.snakeToCamel(e.prop)] = searchData[e.prop];
            }
          })
          if (searchType.indexOf("raw") == -1) {
            delete searchData[e.prop];
          }
        }
      })
      return searchData
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getData();
    },
    // 重置按钮操作
    resetQuery() {
      this.queryParams = this.$options.data().queryParams
      this.getData();
    },
    promoteObjectByValue(array, valueToPromote) {
      const promotedObject = array.find(obj => obj.prop === valueToPromote);
      if (promotedObject) {
        const promotedIndex = array.indexOf(promotedObject);
        array.splice(promotedIndex, 1);
        array.unshift(promotedObject);
      }
      return array;
    },

    getDictName() {
      this.getDicts(`CN_MAP_${this.item.paramObjectName}_${this.item.paramObjectAttr}`).then(response => {
        console.log(response.data)
        if (response.data?.length > 0) {
          this.dictOptions = response.data;
          this.listForm.searchColumn.map((item) => {
            if (this.dictOptions.length > 0 && this.dictOptions.find(e => e.dictValue === item.label))
              item.label = this.dictOptions.find(e => e.dictValue === item.label).dictLabel;
          })


        }
      });
    },
    async getList(val) {
      this.loading = true;
      if (this.item){
        this.getDictName();
      }
      // 追加查询参数
      this.queryParams = {...this.queryParams, ...this.listForm.queryParams};
      await postAction(this.listForm.path, {...this.setQueryParams(), ...this.listForm.extraForm}).then(
        response => {
          this.columns = this.listForm.columns || [];
          if (response.data) {
            if ((this.columns.length == 0) && response.data?.list.length > 0) {
              this.columns = [];
              Object.keys(response.data.list[0]).map((e) => {
                this.columns.push({
                  prop: e,
                  label: e
                })
              })
              if (this.listForm.valueField) {
                this.columns = this.promoteObjectByValue(this.columns, this.listForm.valueField);
              }
              if (this.listForm.showField) {
                this.columns = this.promoteObjectByValue(this.columns, this.listForm.showField);
              }

            }

            this.columns.map((item) => {
              if (this.dictOptions.length > 0 && this.dictOptions.find(e => e.dictValue === item.label))
                item.label = this.dictOptions.find(e => e.dictValue === item.label).dictLabel;
            })

            this.defaultProps.label = this.listForm.showField;
            this.dataList = response.data.list;
            this.total = response.data.total * 1;
            if (val) {
              this.selectData = JSON.parse(val);
            }
          }
          this.loading = false;
        }
      );
    },
    getData() {
      this.loading = true;
      postAction(this.listForm.path, {...this.setQueryParams(), ...this.listForm.extraForm}).then(
        response => {
          if (response.data) {
            this.dataList = response.data.list;
            this.total = response.data.total;
          }
          this.loading = false;
        }
      );
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    async handleRowDblClick(val) {
      this.currentRow = val;
      this.multipleSelection = [val];
      // await this.submitForm();
    },
    handleSelectionChange(val) {
      console.log("Selection", val)
      this.multipleSelection = val;
    },
    // 提交按钮
    submitForm: debounceWrapper(function () {
      if (this.selectData.length > 0) {
        this.$set(this.listForm, 'selected', this.selectData);
        this.listForm.open = false;
        this.$emit('selectedsRow', this.selectData);
      } else {
        this.$message.error("请先选择需要的数据！");
      }
    }),
    // 取消按钮
    cancel() {
      this.listForm.open = false;
    },
  }
}
</script>

<style scoped>

</style>
